﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using DelicateDict.Classes;
using BerkeleyDB;
namespace DelicateDict
{
    public partial class MainForm : Form
    {
        IOFile iof = null;
        DictType CurrentDictType = null;
        int len = 0;
        int OldScroll = 0;  //old value of vscroolbar
        public MainForm()
        {
          

            InitializeComponent();

            //
            len = (WordListView.Height) / WordListView.ItemHeight;
            iof= new IOFile();
            CurrentDictType = iof.DefaultDictType;
        }
        #region Custom method

        private void MainForm_Load(object sender, EventArgs e)
        {
            // Initial WordList
            InitialWordList();
            // searchword 
          searchword = new Classes.SearchWord(wordlist.ArrayWord);
          if (CurrentDictType.DBWord == "Data\\EV_word.index") radiobtnAV.Checked = true;
          if (CurrentDictType.DBWord == "Data\\VE_word.index") radiobtnVA.Checked = true;
          if (CurrentDictType.DBWord == "Data\\custom_word.index") radiobtnCustom.Checked = true;
        }

        private void InitialWordList()
        {
            if (wordlist.ArrayWord.Count <= len)
            {
                foreach (string str in wordlist.ArrayWord)
                    WordListView.Items.Add(str);
                vScrollBar1.Visible = false;
                return;
            }
            vScrollBar1.Visible = true;
            vScrollBar1.Minimum = 0;
            vScrollBar1.Maximum = wordlist.ArrayWord.Count - len;
            vScrollBar1.Value = 0;
            string[] arr = wordlist.LoadWordList(0, len);
            foreach (string str in arr)
             WordListView.Items.Add(str);

        }
        
        public void RefreshListBoxData(string word,bool IsRemove,string DBword)
        {
            if (CurrentDictType.DBWord != DBword) return;
            if (word != string.Empty)
            {
                if (IsRemove)
                    wordlist.ArrayWord.Remove(word);
                else
                {
                    if (searchword.GetIndexSearch(word))
                    {
                        wordlist.ArrayWord.Insert(searchword.left, word);
                    }
                    else
                    {
                        wordlist.ArrayWord.Add(word);
                    }
                }
            }
            ListBoxData(vScrollBar1.Value, len);
              
        }
        private void ReloadWorList()
        {
            LoadWordListandSearchWord(CurrentDictType.DBWord);
        }
        public void ListBoxData(int start, int length)
        {
            
            string[] arr = wordlist.LoadWordList(start, length);
            if (arr == null) return;
                for (int i = 0; i < length; i++)
                {
                    //WordListView.BeginUpdate();
                    try
                    {
                        WordListView.Items[i] = arr[i];
                        // WordListView.EndUpdate();
                    }
                    catch (ArgumentNullException)
                    {
                        //MessageBox.Show(e.Message);
                        return;
                    }
                     // if index out of range
                    catch (IndexOutOfRangeException)
                    {
                        //MessageBox.Show(e.Message);
                        WordListView.Items.RemoveAt(i);
                        //WordListView.Items.Remove(arr[i]);
                        return;
                    }
                    //if total item of wordlistview less than length of array, we add more
                    catch (ArgumentOutOfRangeException)
                    {
                        WordListView.Items.Add(arr[i]);
                        return;
                    }
                }
           
        }
        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void Click1(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {

        }

        private void Update_click(object sender, EventArgs e)
        {
            Form f = new Form();
            f.Text = "Contact";
            f.Show();
        }

        private void About_click(object sender, EventArgs e)
        {
            
            about f = new about();
            f.Show();
            //System.Threading.Thread.Sleep(4000);
            //f.Close();
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {

        }

        private void contact_click(object sender, EventArgs e)
       {
            contact k = new contact();
            k.ShowDialog();
           // System.Threading.Thread.Sleep(4000);
           // k.Close();

        }

        private void toolStrip1_ItemClicked(object sender, EventArgs e)
        {
        }

        private void toolStripDropDownButton1_Click(object sender, EventArgs e)
        {

        }

        private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void change_click(object sender, EventArgs e)
        {
            runbackground l = new runbackground();
            l.Show();
            
        }

        

        private void Speak_click(object sender, EventArgs e) // click vao bieu tuong game
        {
            if (WordListView.SelectedIndex != -1 )
            {
                //sp.SpeakWord(SearchWord.Text);
                sp.SpeakWord(WordListView.SelectedItem.ToString());
            }
        }

        private void click_yourstudy(object sender, EventArgs e) // save lai cac tu vung da tra vao 1 file text hoac word
        {
            MyStudy mystudy = new MyStudy();
            mystudy.ShowDialog();
        }

        private void splitContainer1_Panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void Help_Click(object sender, EventArgs e)
        {

        }

        private void statusStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            int len = (WordListView.Height ) / WordListView.ItemHeight;

            if (OldScroll != vScrollBar1.Value)
            {

                OldScroll = vScrollBar1.Value;
                
                ListBoxData(vScrollBar1.Value, len);

            }
        }

       /* private void SearchWord_TextChanged(object sender, EventArgs e)
        {
            
           //int len = (WordListView.Height ) / WordListView.ItemHeight;
            string inputsearch = SearchWord.Text;
            searchword.GetIndexSearch(inputsearch.Trim());
            int Index = Classes.SearchWord.Index;
            int SelectedIndex = 0;
            if (Index != -1)
            {
                if ((Index - vScrollBar1.Value) < len && Index > vScrollBar1.Value && Index < vScrollBar1.Maximum)
                {
                    SelectedIndex = Index - vScrollBar1.Value;
                    SearchWord.BackColor = Color.White;
                   
                }
                else if (Index < vScrollBar1.Maximum)
                {
                    SearchWord.BackColor = Color.White;
                    vScrollBar1.Value = Index;
                    ListBoxData(vScrollBar1.Value, len);
                    WordListView.SelectedIndex = 0;
                

                }
                else
                {
                    SearchWord.BackColor = Color.White;
                    vScrollBar1.Value = vScrollBar1.Maximum;
                    ListBoxData(vScrollBar1.Value, len);
                    WordListView.SelectedIndex = Index - vScrollBar1.Maximum;      
                }
                
            }
            else
            {
                Index = searchword.left;
                if (!(WordList.ArrayWord[Index].Trim().ToLower().StartsWith(inputsearch.Trim().ToLower())))
                {
                    WordListView.SelectedIndex = -1;
                    SearchWord.BackColor = Color.Orange;
                    System.Media.SystemSounds.Asterisk.Play();
                 
                }
                else
                {
                    SearchWord.BackColor = Color.White;
                }
                if (Index != -1)
                {
                  
                    if ((Index - vScrollBar1.Value) < len && Index > vScrollBar1.Value
                        && Index < vScrollBar1.Maximum)
                    {
                        WordListView.SelectedIndex = Index - vScrollBar1.Value;
                        
                    }
                    else if (Index < vScrollBar1.Maximum)
                    {
                       vScrollBar1.Value = Index;
                       ListBoxData(vScrollBar1.Value, len);
                       WordListView.SelectedIndex = 0;
                        
                    }
                    else
                    {
                        vScrollBar1.Value = vScrollBar1.Maximum;
                        ListBoxData(vScrollBar1.Value, len);
                        WordListView.SelectedIndex = Index - vScrollBar1.Maximum;
                        
                    }
                }
                   
                

            }
          //  MessageBox.Show(SelectedIndex.ToString());
            //WordListView.SelectedIndex = SelectedIndex;
        }*/
        private void SearchWord_TextChanged(object sender, EventArgs e)
        {
            if (SearchWord.Text == null) return;
            string inputsearch = SearchWord.Text;
            searchword.GetIndexSearch(inputsearch.Trim());
            int Index = searchword.Index;
            
            if (Index != -1)
            {
                if ((Index - vScrollBar1.Value) < len && Index > vScrollBar1.Value && Index < vScrollBar1.Maximum)
                {
                    WordListView.SelectedIndex = Index - vScrollBar1.Value;
                    SearchWord.BackColor = Color.White;
                }
                else if (Index < vScrollBar1.Maximum)
                {
                    SearchWord.BackColor = Color.White;
                    vScrollBar1.Value = Index;
                    WordListView.SelectedIndex = 0;

                }
                else
                {
                    SearchWord.BackColor = Color.White;
                    WordListView.SelectedIndex = Index - vScrollBar1.Maximum;
                    vScrollBar1.Value = vScrollBar1.Maximum;
                }
            }
            else
            {
                Index = searchword.left;


                if (!wordlist.ArrayWord[Index].Trim().ToLower().StartsWith(inputsearch.Trim().ToLower()))
                {
                    SearchWord.BackColor = Color.Orange;
                    System.Media.SystemSounds.Asterisk.Play();
                }
                else
                {
                    SearchWord.BackColor = Color.White;
                }
                if (Index != -1)
                {
                    if ((Index - vScrollBar1.Value) < len && Index > vScrollBar1.Value
                        && Index < vScrollBar1.Maximum)
                    {
                        WordListView.SelectedIndex = Index - vScrollBar1.Value;
                    }
                    else if (Index < vScrollBar1.Maximum)
                    {
                        vScrollBar1.Value = Index;
                        WordListView.SelectedIndex = 0;
                    }
                    else
                    {
                        WordListView.SelectedIndex = Index - vScrollBar1.Maximum;
                        vScrollBar1.Value = vScrollBar1.Maximum;
                    }
                }

            }
        }

        private void WordListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            if (WordListView.SelectedIndex != -1)
            {
                IOFile iof = new IOFile();
                string ImagePath = Environment.CurrentDirectory + @"\WebBrowserContent";
                string Index = WordListView.SelectedItem.ToString();

               //get mean from database 
                string mean = _Database.GetMean(Index, iof.DefaultDictType);
                //setting color
                DecorateMean.SetColor(ref mean);
                //get content html
                string HtmlDocument = File.ReadAllText(Environment.CurrentDirectory + @"\WebBrowserContent\pattern.html");
                ImagePath =  ImagePath.Replace('\\','/');
                HtmlDocument = HtmlDocument.Replace("path", ImagePath);

                // insert content into html
                HtmlDocument = HtmlDocument.Replace("MeanSettingColor", mean);
                // insert link of image which have same name as searching word. All Image Extension is jpg.
                HtmlDocument = HtmlDocument.Replace("ImageName", Index);
                //File.WriteAllText(Environment.CurrentDirectory + @"\WebBrowserContent\browserContent.html", HtmlDocument);
                //webBrowserContent.Url = new System.Uri(Environment.CurrentDirectory + @"\WebBrowserContent\browserContent.html");     
                webBrowserContent.DocumentText = HtmlDocument;

                
            }
        }

        private void WordListView_KeyDown(object sender, KeyEventArgs e)
        {
           // int len = (WordListView.Height) / WordListView.ItemHeight;
            if (vScrollBar1.Value > vScrollBar1.Minimum && e.KeyCode == Keys.Up && WordListView.SelectedIndex==0)
            {
                vScrollBar1.Value = vScrollBar1.Value - 1;
                 ListBoxData(vScrollBar1.Value, len);
            }
            if (vScrollBar1.Value < vScrollBar1.Maximum && e.KeyCode == Keys.Down && WordListView.SelectedIndex == len-1)
            {
                
                vScrollBar1.Value = vScrollBar1.Value + 1; 
                 ListBoxData(vScrollBar1.Value, len);
            }
        }

        private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
        {
  
            WordListView.SelectedIndex = -1;
           // ListBoxData(vScrollBar1.Value, len);
            
        }

        private void MainForm_Resize(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                notifyIcon1.ShowBalloonTip(2, "Notify", "DelicateDict's running at system tray", ToolTipIcon.Info);
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
            WindowState = FormWindowState.Normal;
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            about aboutForm = new about();
            aboutForm.ShowDialog();
        }

        private void mainDictionaryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
            WindowState = FormWindowState.Normal;
        }

        private void Options_Click(object sender, EventArgs e)
        {
            Options op = new Options();
            
            //Truyen ham delegate update listbox tren mainform
            op.refreshwordlistbox = new DelicateDict.Options.RefreshWordList(RefreshListBoxData);
            op.reloadwordlistbox = new DelicateDict.Options.ReloadWordList(ReloadWorList);
            //
            op.ShowDialog();
        }

        private void radiobtnAV_CheckedChanged(object sender, EventArgs e)
        {
            if (radiobtnAV.Checked)
            {
                foreach (DictType dt in iof.GetAllDictType())
                    if (dt.DBWord == "Data\\EV_word.index")
                    {
                        CurrentDictType = dt;
                        break;
                    }
                iof.DefaultDictType = CurrentDictType;
                LoadWordListandSearchWord(CurrentDictType.DBWord);
            }                 
        }

        private void radiobtnVA_CheckedChanged(object sender, EventArgs e)
        {
            if (radiobtnVA.Checked)
            {

                foreach (DictType dt in iof.GetAllDictType())
                    if (dt.DBWord == "Data\\VE_word.index")
                    {
                        CurrentDictType = dt;
                        break;
                    }
                iof.DefaultDictType = CurrentDictType;
                LoadWordListandSearchWord(CurrentDictType.DBWord);
            }
        }

        private void radiobtnCustom_CheckedChanged(object sender, EventArgs e)
        {
            if (radiobtnCustom.Checked)
            {
                foreach(DictType dt in iof.GetAllDictType())
                    if (dt.DBWord == "Data\\custom_word.index")
                    {
                        CurrentDictType = dt;
                        break;
                    }
                iof.DefaultDictType = CurrentDictType;
                LoadWordListandSearchWord(CurrentDictType.DBWord);
            }         
        }
        private void LoadWordListandSearchWord(string wordlistPath)
        {
            wordlist.CloseWordList();
            wordlist = new WordList(wordlistPath);
            WordListView.Items.Clear();
            InitialWordList();
            searchword.CloseSearchWord();
            searchword = new SearchWord(wordlist.ArrayWord);
        }

        private void SearchWord_KeyDown(object sender, KeyEventArgs e)
        {
            if (vScrollBar1.Value > vScrollBar1.Minimum && e.KeyCode == Keys.Up)
            {
                vScrollBar1.Value = vScrollBar1.Value - 1;
                ListBoxData(vScrollBar1.Value, len);
            }
            if (vScrollBar1.Value < vScrollBar1.Maximum && e.KeyCode == Keys.Down)
            {

                vScrollBar1.Value = vScrollBar1.Value + 1;
                ListBoxData(vScrollBar1.Value, len);
            }
        }

        private void addToMyStudyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(WordListView.SelectedIndex == -1) 
            {
                MessageBox.Show("No word has seleted");
                return;
            }
            //load iof class
            IOFile iof = new IOFile();
            // load sqlite db class
            SQLiteDB mystudy = new SQLiteDB();
            //insert
            string word = WordListView.SelectedItem.ToString();
            mystudy.Insert(word, _Database.GetMean(word, iof.DefaultDictType), iof.DefaultDictType.DbName);
        }

    }
}
